import {
  SECOND_FILTER_MORE_MAP,
  MAIN_FILTER,
  SEARCH_FILTER,
  FILTER_SEARCH_Y_IMG,
  FILTER_SEARCH_D_IMG,
} from "../../constant/index";
import api from "../../utils/api";

Component({
  options: {
    addGlobalClass: true,
    pureDataPattern: /^_/, // 指定所有 _ 开头的数据字段为纯数据字段
  },
  /**
   * 组件的属性列表
   */
  properties: {
    typeList: {
      type: Array,
      value: []
    },
    provincesList: {
      type: Array,
      value: []
    },
    areaTxt: {
      type: String,
    },
    catId: {
      type: String,
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    searchImgDefault: FILTER_SEARCH_D_IMG,
    searchImgSelect: FILTER_SEARCH_Y_IMG,
    mainFilter: MAIN_FILTER,
    searchFilter: SEARCH_FILTER,
    filterMore: SECOND_FILTER_MORE_MAP["down"],
    modalType: "",
    provinceChoose: -100,
    vaccineCategoryId: -100,
    cityList: [],
    isShow: false,
    isShowBg: false,
    _currentSecondFilterSort: 0, // 当前二级筛选项的sort
    _filterResult: {
      areaId: "",
      minDistanceToMax: null,
      minPayPriceToMax: null,
      gender: null,
      vaccineCategoryId: null,
      "injectObjects[]": null,
    },
  },

  lifetimes: {
    ready() {
      const { mainFilter, areaTxt, catId } = this.data;
      // 如果 areaTxt catId有值 说明要更新filter
      if (areaTxt) {
        mainFilter[0].txt = areaTxt;
        this.setData({
          mainFilter,
        });
      }
      if (catId) {
        this.setData({
          vaccineCategoryId: +catId,
        });
      }
      this.selectorQuery();
      catId && this.pageScrollTo()
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * @description: 获取城市
     * @param {*} provinceId
     */
    getCityList(provinceId) {
      api.areaCities({
        data: {
          provinceId,
        },
        success: (res) => {
          if (+res.code === 0) {
            this.setData({
              cityList: res.data,
            });
          }
        },
      });
    },
    /**
     * @description: 展示全部次选择项
     * @param {*} e
     */
    onShowAllFilter(e) {
      const type = e.currentTarget.dataset.type;
      const nextType = type === "up" ? "down" : "up";
      this.pageScrollTo();
      this.setData({
        filterMore: SECOND_FILTER_MORE_MAP[nextType],
        isShowBg: type === "down",
      });
    },
    /**
     * @description: 点击一级筛选项
     * @param {*} e
     */
    filterMainItem(e) {
      const { item } = e.currentTarget.dataset;

      // 处理城市
      if (item.type === "city") {
        this.handleCity(item);
      }
      // 处理筛选
      if (item.type === "search") {
        this.handleSearch(item);
      }
      // 处理距离
      if (item.type === "distance") {
        this.handleDistance(item);
      }
      // 处理价格
      if (item.type === "price") {
        this.handlePrice(item);
      }
      this.pageScrollTo();
    },

    /**
     * @description: 处理城市项
     */
    handleCity(item) {
      const arr = [
        {
          type: "city",
          data: {
            iconType: this.handleIconType(item.iconType),
            active: true,
          },
        },
        {
          type: "search",
          data: {
            iconType: "up",
            active: false,
          },
        },
      ];
      const mainFilter = this.handleMianFilterData(arr);
      this.setData({
        modalType: item.type,
        isShow: item.iconType === "down",
        isShowBg: item.iconType === "down",
        mainFilter,
        filterMore: SECOND_FILTER_MORE_MAP["down"],
      });
    },

    /**
     * @description: 处理最右边的筛选项
     * @param {*} item
     */
    handleSearch(item) {
      const arr = [
        {
          type: "city",
          data: {
            iconType: "down",
          },
        },
        {
          type: "search",
          data: {
            iconType: this.handleIconType(item.iconType),
            active: true,
          },
        },
      ];
      const mainFilter = this.handleMianFilterData(arr);
      this.setData({
        modalType: item.type,
        isShow: !item.iconType || item.iconType === "up",
        isShowBg: !item.iconType || item.iconType === "up",
        mainFilter,
      });
    },

    /**
     * @description: 处理距离
     * @param {*} item
     */
    handleDistance(item) {
      const { _filterResult } = this.data;
      const arr = [
        {
          type: "distance",
          data: {
            iconType: this.handleIconType(item.iconType),
            active: true,
          },
        },
        {
          type: "price",
          data: {
            iconType: "",
            active: false,
          },
        },
        {
          type: "city",
          data: {
            iconType: "down",
          },
        },
        {
          type: "search",
          data: {
            iconType: "",
          },
        },
      ];
      const mainFilter = this.handleMianFilterData(arr);
      _filterResult["minDistanceToMax"] =
        !item.iconType || item.iconType === "up" ? false : true;
      _filterResult["minPayPriceToMax"] = null;
      this.triggerEvent("onSearch", _filterResult);
      this.setData({
        mainFilter,
        isShow: false,
        isShowBg: false,
      });
    },

    /**
     * @description: 处理价格
     * @param {*} item
     */
    handlePrice(item) {
      const { _filterResult } = this.data;
      const arr = [
        {
          type: "price",
          data: {
            iconType: this.handleIconType(item.iconType),
            active: true,
          },
        },
        {
          type: "distance",
          data: {
            iconType: "",
            active: false,
          },
        },
        {
          type: "city",
          data: {
            iconType: "down",
          },
        },
        {
          type: "search",
          data: {
            iconType: "",
          },
        },
      ];
      const mainFilter = this.handleMianFilterData(arr);
      _filterResult["minPayPriceToMax"] =
        !item.iconType || item.iconType === "up" ? false : true;
      _filterResult["minDistanceToMax"] = null;
      this.triggerEvent("onSearch", _filterResult);
      this.setData({
        mainFilter,
        isShow: false,
        isShowBg: false,
      });
    },

    /**
     * @description: 点击省份
     * @param {*} e
     */
    chooseProvince(e) {
      const { item, modaltype } = e.currentTarget.dataset;
      const { _filterResult } = this.data;
      if (item.id < 0) {
        const arr = [
          {
            type: modaltype,
            data: {
              txt: item.name,
              iconType: "down",
            },
          },
        ];
        const mainFilter = this.handleMianFilterData(arr);
        _filterResult["areaId"] = "";
        this.triggerEvent("onSearch", _filterResult);
        this.setData({
          provinceChoose: +item.id,
          isShow: false,
          isShowBg: false,
          mainFilter,
          cityChoose: "",
          cityList: [],
          _filterResult,
        });
      } else {
        this.getCityList(item.id);
        this.setData({
          provinceChoose: +item.id,
        });
      }
    },
    /**
     * @description: 点击城市
     * @param {*} e
     */
    chooseCity(e) {
      const { item, modaltype } = e.currentTarget.dataset;
      const { _filterResult } = this.data;
      const arr = [
        {
          type: modaltype,
          data: {
            txt: item.name,
            iconType: "down",
          },
        },
      ];
      const mainFilter = this.handleMianFilterData(arr);
      _filterResult["areaId"] = item.id;
      this.triggerEvent("onSearch", _filterResult);
      this.setData({
        cityChoose: +item.id,
        isShow: false,
        isShowBg: false,
        mainFilter,
      });
    },
    /**
     * @description: 点击筛选项
     */
    chooseSearch(e) {
      const { index, childrenindex } = e.currentTarget.dataset;
      const searchFilter = this.handleSearchFilter(index, childrenindex);
      this.setData({
        searchFilter,
      });
    },
    /**
     * @description: 点击筛选重置
     */
    resetSearch(e) {
      const { modaltype } = e.currentTarget.dataset;
      const { _filterResult } = this.data;
      const mainFilter = this.handleMianFilterData([
        {
          type: modaltype,
          data: {
            iconType: "",
            active: false,
          },
        },
      ]);
      const searchFilter = this.data.searchFilter.map((item) => {
        const children = item.children.map((itemsub, index) => {
          return {
            ...itemsub,
            active: index === 0,
          };
        });
        return {
          label: item.label,
          children,
        };
      });

      _filterResult["injectObjects[]"] = null;
      _filterResult["gender"] = null;
      this.triggerEvent("onSearch", _filterResult);
      this.setData({
        searchFilter,
        isShow: false,
        isShowBg: false,
        mainFilter,
      });
    },
    /**
     * @description: 点击筛选确认
     */
    comfirmSearch(e) {
      const { modaltype } = e.currentTarget.dataset;
      const { _filterResult, searchFilter } = this.data;
      const result = [];
      const mainFilter = this.handleMianFilterData([
        {
          type: modaltype,
          data: {
            iconType: "",
            active: true,
          },
        },
      ]);
      searchFilter.forEach((item) => {
        item.children.forEach((itemsub) => {
          if (itemsub.active) {
            result.push(itemsub.value);
          }
        });
      });

      _filterResult["injectObjects[]"] = result[0];
      _filterResult["gender"] = result[1];
      this.triggerEvent("onSearch", _filterResult);
      this.setData({
        searchFilter,
        isShow: false,
        isShowBg: false,
        mainFilter,
      });
    },
    /**
     * @description: 处理三角形的类型
     */
    handleIconType(type) {
      if (!type) return "down";
      if (type === "down") return "up";
      if (type === "up") return "down";
    },
    /**
     * @description: 处理筛选项
     * @param {*} i
     * @param {*} childreni
     */
    handleSearchFilter(i, childreni) {
      return this.data.searchFilter.map((item, index) => {
        if (i === index) {
          const children = this.handleSearchFilterItem(
            item.children || [],
            childreni
          );
          return {
            label: item.label,
            children,
          };
        } else {
          return item;
        }
      });
    },
    /**
     * @description: 次筛选项
     * @param {*} data
     * @param {*} childreni
     */
    handleSearchFilterItem(data = [], childreni) {
      return data.map((itemsub, subIndex) => {
        return {
          ...itemsub,
          active: childreni === subIndex && !itemsub.active ? true : false,
        };
      });
    },
    /**
     * @description: 处理一级筛选数据
     */
    handleMianFilterData(data = []) {
      const { mainFilter } = this.data;
      data.forEach((el) => {
        mainFilter.forEach((item, index, arr) => {
          if (item.type === el.type) {
            arr[index] = {
              ...item,
              ...el.data,
            };
          }
        });
      });
      return mainFilter;
    },

    onSecondItem(e) {
      const { index, item } = e.currentTarget.dataset;
      const { _filterResult, _currentSecondFilterSort, vaccineCategoryId } =
        this.data;
      // 点击相同id退出
      if (vaccineCategoryId === item.id) return;
      _filterResult["vaccineCategoryId"] = item.id > 0 ? item.id : "";

      this.triggerEvent("onSecondSearch", {
        _filterResult,
        index,
        _currentSecondFilterSort:
          item.id > 0 ? _currentSecondFilterSort + 50 : item.sortIndex,
      });
      this.pageScrollTo();
      this.setData({
        vaccineCategoryId: item.id,
        _currentSecondFilterSort: _currentSecondFilterSort + 50,
        isShowBg: false,
        filterMore: SECOND_FILTER_MORE_MAP["down"],
      });
    },
    /**
     * @description: 关闭蒙层
     */
    closeModel() {
      const arr = [
        {
          type: "city",
          data: {
            iconType: "down",
          },
        },
        {
          type: "search",
          data: {
            iconType: "up",
            active: false,
          },
        },
      ];
      const mainFilter = this.handleMianFilterData(arr);
      this.setData({
        filterMore: SECOND_FILTER_MORE_MAP["down"],
        isShowBg: false,
        isShow: false,
        mainFilter,
      });
    },

    /**
     * @description:
     * @param {*}
     * @return {*}
     */
    selectorQuery() {
      const query = wx.createSelectorQuery().in(this);
      query.select("#filter-box").boundingClientRect();
      query.exec((res) => {
        const [result = {}] = res || [];
        result.top > 0 &&
          this.setData({
            scrollTop: result.top,
          });
      });
    },
    pageScrollTo() {
      const query = wx.createSelectorQuery().in(this);
      query.select("#filter-box").boundingClientRect();
      query.exec((res) => {
        const [result = {}] = res || [];
        result.top > 0 &&
          wx.pageScrollTo({
            scrollTop: this.data.scrollTop,
          });
      });
    },
  },
});
